package net.sf.borg.ui.calendar;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import net.sf.borg.model.CalWriter;

/**
 * HTMLCalExporter
 * 
 * This class provides a single functional method, exportCal()
 * which prompts the user for a file of type fileExt.  Then a
 * representation of the calendar between startDate and endDate
 * is written to the given file with a format based on calWriter
 * 
 * Created in UF Software Engineering - Summer 2009
 * @author Matthew Carroll
 */

public class CalExporter {

	//------- Static Singleton Support ----------//
	public static CalExporter instance = null;
	
	public static CalExporter getInstance()
	{
		if(instance == null) {
			instance = new CalExporter();
		}
		
		return instance;
	}
	
	
	//---- File Filter Used To Limit HTML Files ----///
	private class HTMLFileFilter extends FileFilter
	{

		@Override
		public boolean accept(File f) {
			if( f.getName().toLowerCase().endsWith(".html") || f.isDirectory() ) {
				return true;
			}else{
				return false;
			}
		}

		@Override
		public String getDescription() {
			return ".html (Hypertext Markup Language Files)";
		}
		
	}
	
	
	//--- HTMLCalExporter Instance Functionality ---//
	//Constructor
	private CalExporter() {}
	
	
	private Boolean validFileName(String name, String fileExt)
	{
		if(!name.endsWith(fileExt)) return false;
		
		String nameToValidate = name.substring(0, name.lastIndexOf(fileExt)).trim();//validate name without extension and no outer whitespace
		
		if(nameToValidate.length() == 0) return false; //only restriction on name is that it is non-blank
		
		return true;
	}
	
	/*
	 * Prompts user for file location and name, validates name, then writes a calendar representation to that file
	 * consisting of dates/appointments starting at startDate and ending at endDate
	 */
	public void exportCal(Date startDate, Date endDate, CalWriter calWriter, String fileExt)
	{		
		//Get File to save HTML file
		final 	JFileChooser fc = new JFileChooser();
		File 	file 			= null;		//user-chosen file in which to write
		int 	returnVal;					//return value from fc's save dialog
		Boolean validName 		= false; 	//is chosen file name valid
		String 	fileName 		= "";		//user-chosen file name
		
		fc.setAcceptAllFileFilterUsed(false);
		fc.setFileFilter(new HTMLFileFilter());
		
		//Keep asking user for file until EITHER:
		//	- file is valid
		//	- user presses cancel
		while(!validName) 
		{
			returnVal = fc.showSaveDialog(null);
			
			if (returnVal == JFileChooser.APPROVE_OPTION) 
			{
				try {					
					file = fc.getSelectedFile();
					fileName = file.getName().toLowerCase().trim();
					
					if( validName = validFileName(fileName, fileExt) ) {
						file.createNewFile();
						
						//make sure file is writable, else return
						if(!file.canWrite()) {
							System.out.println("[CalExporter] - Could not write to specified file.");
							return;
						}
					}else{
						//Inform user that choice of file had a validation problem
						JOptionPane.showMessageDialog(null, "Please choose a non-blank filename ending in " + fileExt, "File Error", JOptionPane.ERROR_MESSAGE);
					}
				}catch (IOException e) {
					System.out.println("[CalExporter] - Could not write to file: " + e);
					return;
				}
	        } else {
	        	System.out.println("[CalExporter] - User declined calendar export");
	        	return;
	        }
		}

		//Init filewrite stream
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter( new FileWriter(file) );
		}catch (Exception e) {
			System.out.println("[CalExporter] - Could not initialize buffered writer for file: " + e);
			return;
		}
		
	    //Write Calendar Representation
		calWriter.writeCal(bw, startDate, endDate);
	    
		//Close file write stream
		try {
			bw.close();
		}catch (IOException e) {
			System.out.println("[CalExporter] - Could not close calendar export file: " + e);
			return;
		}
		file = null;
	}
	
}
